package biz.inspeed.test.concurrent;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;

import biz.inspeed.test.tool.CommonUtil;

public class Main1026 {
	public static volatile boolean on = false;
	/**
	 * @param args
	 * @throws NoSuchFieldException 
	 * @throws SecurityException 
	 */
	public static void main(String[] args) throws Exception {
		Timer timer = new Timer();
		timer.schedule(new TestTimer1026(), 0, 1000);
		new PThread(timer).start();
		analise(timer);
	}
	
	public static void analise(Timer timer) throws Exception{
		Field field = Timer.class.getDeclaredField("queue");
		field.setAccessible(true);
		String className = field.getGenericType().toString();
//		System.out.println(className);
		Object object = field.get(timer);
//		System.out.println(object);
		System.out.println(StringUtils.repeat("+-", 50));
		Class<?> forName = Class.forName("java.util.TaskQueue");
//		System.out.println(forName.getCanonicalName());
		
		Method method = forName.getDeclaredMethod("size",null);
		method.setAccessible(true);
		Object invoke = method.invoke(object, null);
		System.out.println("TaskQueue.size: " + invoke);
		
	}
	
	static class PThread extends Thread{
		private Timer timer;
		public PThread(Timer timer){
			this.timer = timer;
		}
		@Override
		public void run() {
			while(true){
				try {
					Main1026.analise(timer);
					TimeUnit.SECONDS.sleep(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}

class TestTimer1026 extends TimerTask {
 static 	int index = 0;
	@Override
	public void run() {
		index ++;
		
		if(index % 10 == 0){
			Main1026.on = true;
		}else{
			Main1026.on = false;
		}
		
		if(Main1026.on){
			try {
				TimeUnit.SECONDS.sleep(10);
				System.out.println(StringUtils.repeat('=', 50));
				System.out.println(CommonUtil.getCurrentTime());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else{
			System.out.println(CommonUtil.getCurrentTime());
		}
		
	}
}
